<style lang="less" scoped>
.switch-status {
  display: block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 2px solid #fff;
  background: #09ee3f;
  box-shadow: 0 0 inset 10px rgba(0, 0, 0, 0.8);
  &.close {
    background: #999;
  }
}

.basic-info {
  height: 1.48rem !important;
  .info-item {
    align-items: center;
  }
  /deep/.el-table__body-wrapper td {
    border-width: none !important;
    border-top: 2px solid #02123e !important;
  }
  .iconfont {
    font-size: 12px !important;
    color: #428dff;
    cursor: pointer;
  }
}
.icon {
  .iconfont {
    font-size: 18px !important;
    cursor: pointer;
    color: #7af1c8;
  }
}
.disabeled {
  color: #999 !important;
  // pointer-events:none;
}
.el-dialog__body {
  position: relative;
  height: 160px !important;
}
.seriesData {
  padding: 30px 0;
  // background: #fff;
  color: #21e67a;
  font-size: 43px;
  justify-content: center;
  width: 100%;
}
.stateList {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}
</style>
<template>
  <div class="device-detail-basic">
    <el-row :gutter="20" v-if="isWireless()">
      <el-col :span="24" class="fl-bw">
        <div class="main-blk basic-info">
          <dl class="info-item flex">
            <dt>更新时间：</dt>
            <dd class="flex-1">{{ deviceDetail.normalUpdateTime || "-" }}</dd>
          </dl>
          <dl class="info-item flex">
            <dt>设备名称：</dt>
            <dd class="flex-1">{{ deviceDetail.name || "-" }}</dd>
          </dl>

          <dl class="info-item flex">
            <dt>设备编号：</dt>
            <dd class="flex-1">{{ deviceDetail.number || "-" }}</dd>
          </dl>
          <dl class="info-item flex">
            <dt>设备版本：</dt>
            <dd class="flex-1">{{ deviceDetails.version || "-" }}</dd>
          </dl>
          <dl class="info-item flex">
            <dt>电池电量：</dt>
            <dd class="flex-1">{{ deviceDetails.electricity || "-" }}</dd>
          </dl>
          <dl class="info-item flex">
            <dt>信号强度：</dt>
            <dd class="flex-1">{{ deviceDetails.signalPercentage || "-" }}</dd>
          </dl>
          <dl class="info-item flex">
            <dt>测量值：</dt>
            <dd class="flex-1">{{ deviceDetail.waterValue || "-" }}</dd>
          </dl>
          <dl class="info-item flex">
            <dt>单 位：</dt>
            <dd class="flex-1">{{ deviceDetail.unit || "-" }}</dd>
          </dl>
        </div>

        <div class="main-blk basic-info">
          <dl class="info-item flex">
            <dt>报警上限值：</dt>
            <dd class="flex-1">
              {{ deviceDetails.upperLimitAlarmSettingValue || "-" }}
            </dd>
          </dl>
          <dl class="info-item flex">
            <dt>报警下限值：</dt>
            <dd class="flex-1">
              {{ deviceDetails.lowerLimitAlarmSetPoint || "-" }}
            </dd>
          </dl>
          <dl class="info-item flex">
            <dt>安装位置：</dt>
            <dd class="flex-1">{{ deviceDetail.position || "-" }}</dd>
          </dl>
          <dl class="info-item flex">
            <dt>报警电话：</dt>
            <dd class="flex-1">{{ deviceDetail.alarmPhone || "-" }}</dd>
          </dl>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="20" v-else>
      <el-col :span="24" class="fl-bw">
        <div class="main-blk basic-info stateList">
          <dl class="info-item flex">
            <dt>设备名称：</dt>
            <dd class="flex-1">{{ deviceDetail.name || "-" }}</dd>
          </dl>
          <dl class="info-item flex">
            <dt>设备编号：</dt>
            <dd class="flex-1">{{ deviceDetail.number || "-" }}</dd>
          </dl>
          <dl class="info-item flex">
            <dt>设备状态：</dt>
            <dd class="flex-1" v-if="deviceDetail.currentstate">
              <i
                :class="'dot ' + stateArr[deviceDetail.currentstate - 1].class"
              ></i>
              {{ stateArr[deviceDetail.currentstate - 1].name || "-" }}
            </dd>
          </dl>
          <dl class="info-item flex">
            <dt>设备类型：</dt>
            <dd class="flex-1">{{ deviceDetail.deviceTypeName || "-" }}</dd>
          </dl>
          <dl class="info-item flex">
            <dt>安装位置：</dt>
            <dd class="flex-1">{{ deviceDetail.position || "-" }}</dd>
          </dl>
          <dl class="info-item flex">
            <dt>报警电话：</dt>
            <dd class="flex-1">{{ deviceDetail.alarmPhone || "-" }}</dd>
          </dl>
          <dl class="info-item flex">
            <dt>更新日期：</dt>
            <dd class="flex-1">{{ deviceDetail.normalUpdateTime || "-" }}</dd>
          </dl>

          <template v-if="classify == 10">
            <dl class="info-item flex">
              <dt>控制柜状态：</dt>
              <dd class="flex-1" v-if="deviceDetail.controlCabinetStatus">
                <i
                  :class="
                    'dot ' +
                      stateArr2[deviceDetail.controlCabinetStatus - 1].class
                  "
                ></i>
                {{ stateArr2[deviceDetail.controlCabinetStatus - 1].name }}
                / {{ deviceDetail.controlCabinetHandleStatus || "-" }}
              </dd>
              <dd class="flex-1" v-else>-/-</dd>
            </dl>
            <!-- <dl class="info-item flex">
							<dt>控制柜手自动状态：</dt>
							<dd class="flex-1">{{deviceDetail.controlCabinetHandleStatus || '-'}}</dd>
						</dl> -->
          </template>
          <template v-if="deviceDetail.deviceType == '35'">
            <dl class="info-item flex">
              <dt>备 &nbsp; &nbsp; 注：</dt>
              <dd class="flex-1">{{ deviceDetail.remark || "-" }}</dd>
            </dl>
            <dl class="info-item flex">
              <dt>温度：</dt>
              <dd class="flex-1">{{ fireStatus.temperature || "-" }}℃</dd>
            </dl>
            <dl class="info-item flex">
              <dt>温度状态：</dt>
              <dd class="flex-1">
                {{ fireStatus.temperatureState == 1 ? "报警 " : "正常" || "-" }}
              </dd>
            </dl>
            <dl class="info-item flex">
              <dt>烟雾状态：</dt>
              <dd class="flex-1">
                {{ fireStatus.smokeState == 1 ? "报警 " : "正常" || "-" }}
              </dd>
            </dl>
            <dl class="info-item flex">
              <dt>灭火装置状态：</dt>
              <dd class="flex-1">
                {{
                  fireStatus.fireExtinguishingDeviceState == 1
                    ? "已喷发 "
                    : "正常" || "-"
                }}
              </dd>
            </dl>
          </template>

          <dl class="info-item flex" v-if="deviceDetail.deviceType == 19">
            <dt>分闸状态：</dt>
            <dd class="flex-1" v-if="deviceDetail.openingState == 1">
              <i class="dot green"></i> 开
            </dd>
            <dd class="flex-1" v-else><i class="dot gray"></i> 关</dd>
          </dl>
        </div>
        <div class="main-blk basic-info" v-if="deviceDetail.deviceType == '30'">
          <template>
            <dl class="info-item flex icon">
              <dt>主动采集：</dt>
              <i
                :title="
                  deviceDetail.currentstate == 3 ? '设备已离线无法操作' : ''
                "
                :class="
                  deviceDetail.currentstate == 3
                    ? `disabeled iconfont`
                    : 'iconfont'
                "
                @click="setupNumber('01')"
                >&#xe627;</i
              >
            </dl>
            <dl
              class="info-item flex"
              v-for="(item, index) in variableList"
              :key="index"
            >
              <dt>{{ item.name }}：</dt>
              <dd class="flex-1" v-if="item.name !== '控制切换'">
                {{ item.number || "--" }}
                <i
                  :title="
                    deviceDetail.currentstate == 3 ? '设备已离线无法操作' : ''
                  "
                  :class="
                    deviceDetail.currentstate == 3
                      ? `disabeled iconfont`
                      : 'iconfont'
                  "
                  @click="setupNumber(item)"
                  >&#xe9bc;</i
                >
                {{ deviceDetail.unit }}
              </dd>
              <dd class="flex-1" v-else>
                {{
                  item.number == 1
                    ? "自动"
                    : item.number == 2
                    ? "关闭"
                    : "手动开"
                }}
                <i
                  :class="
                    deviceDetail.currentstate == 3
                      ? `disabeled iconfont`
                      : 'iconfont'
                  "
                  @click="setupNumber(item)"
                  >&#xe9bc;</i
                >
              </dd>
            </dl>
          </template>
        </div>
      </el-col>
    </el-row>
    <!-- <el-col :span="12">
				<div class="main-blk basic-stat">
					<div id="alarmChart" v-if="alarmData.todayCurrentCount"></div>
				</div>
			</el-col> -->
    <!-- </el-row> -->
    <template v-if="classify != 7">
      <template v-if="classify != 19">
        <div class="mt-20 flex v-c">
          <div class="recent-week flex-1 text-right">
            <el-button
              v-if="typeJudgment()"
              type="primary"
              @click="exportAction"
            >
              历史数据导出</el-button
            >
            <a
              class="item"
              :class="{ active: activeDateIndex == index }"
              href="javascript:;"
              v-for="(item, index) in recentWeek"
              :key="index"
              @click="changeDate(item, index)"
              >{{ item.month }}月{{ item.date }}日</a
            >
          </div>
        </div>
        <div
          class="main-blk mt-10"
          v-for="(item, index) in dataList"
          :key="index"
        >
          <div class="flex">
            <h2 class="title flex-1">{{ item.displayName }}</h2>
            <p class="fs-12" style="opacity: 0.5">
              滚动鼠标缩放，按住Shift建拖动鼠标左右平移
            </p>
          </div>
          <el-row class="chart-row d-flex" :gutter="20">
            <el-col :span="6" v-if="!typeJudgment()">
              <div :id="'barChart' + index" v-if="poolShowType != '水压'"></div>
              <div :id="'gaugeChart' + index" v-else></div>
            </el-col>
            <div :span="6" class="fl-bw" v-else-if="!isWireless()">
              <div class="fl-bw seriesData">
                {{ seriesData }}{{ deviceDetail.unit }}
              </div>
            </div>
            <div>
              <div :id="'lineChart' + index" style="width:100%"></div>
            </div>
          </el-row>
        </div>
      </template>
      <template v-else>
        <div class="main-blk mt-10">
          <h2 class="title">开关列表</h2>
          <el-table
            :data="switchList"
            class="mt-10"
            style="width: 100%;"
            v-loading="switchLoading"
          >
            <el-table-column
              prop="number"
              label="设备号"
              width="80"
            ></el-table-column>
            <el-table-column
              prop="name"
              label="设备名称"
              min-width="60"
            ></el-table-column>
            <el-table-column
              prop="position"
              label="安装位置"
              min-width="120"
            ></el-table-column>
            <el-table-column
              prop="installtime"
              label="安装时间"
              min-width="80"
            ></el-table-column>
            <el-table-column
              prop="transDeviceCode"
              label="传输装置编码"
              min-width="80"
            ></el-table-column>
            <el-table-column prop="currentstate" label="状态" width="60">
              <template slot-scope="scope">
                <span
                  class="switch-status"
                  v-if="scope.row.currentstate == 1"
                ></span>
                <span class="switch-status close" v-else></span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </template>

    <el-dialog
      class="remote-modal"
      v-if="setupModalVisible"
      title="编辑"
      :visible.sync="setupModalVisible"
      :width="600 + 'px'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <el-form
        label-position="top"
        label-width="80px"
        style="height: 100px;"
        :rules="rules"
        ref="ruleForm"
        :model="ruleForm"
      >
        <el-form-item
          label="请输入数据"
          prop="settingNumber"
          v-if="ruleForm.instructions !== '08'"
        >
          <el-input v-model="ruleForm.settingNumber" placeholder="-"></el-input>
        </el-form-item>
        <el-form label="请选择数据" prop="settingNumber" v-else>
          <el-select v-model="ruleForm.settingNumber" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form>
        <el-form-item class="p-right">
          <el-button @click="setupModalVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 导出 start -->
    <el-dialog
      class="remote-modal"
      v-if="exportVisible"
      title="历史数据导出"
      :visible.sync="exportVisible"
      :width="600 + 'px'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <device-export :number="number"></device-export>
    </el-dialog>
    <!-- 导出 end -->
  </div>
</template>
<script>
import deviceExport from "./deviceExport.vue";
import HighCharts from "highcharts";
import highchartsMore from "highcharts/highcharts-more";
highchartsMore(HighCharts);
// 消防水池 高位消防水箱 都是水位， 消防栓和末端试水装置都是水压
let waterGageTypes = ["消防栓", "消火栓", "末端试水装置"];
let poolShowType = "";
let socket = null;
function renderSpline(opts) {
  HighCharts.setOptions({
    timezoneOffset: -8,
  });
  let { id, chartData, scale, width, height } = opts;
  scale = scale || 1;
  if (!chartData) return;
  width = scale * width;
  height = scale * height;
  let unit = opts.unit ? opts.unit : "";
  let data = chartData;
  let options = {
    lang: {
      resetZoom: "还原",
    },
    credits: {
      enabled: false,
    },
    colors: ["#5AD8A6", "#F6BD16", "#5B8FF9", "#9270CA"],
    chart: {
      type: "spline",
      width: width,
      height: height,
      backgroundColor: "transparent",
      spacing: 0,
      margin: [50 * scale, 0, 30, 80 * scale],
      zoomType: "x",
      panning: true,
      panKey: "shift",
    },
    mapNavigation: {
      enabled: true,
      enableButtons: false,
    },
    title: {
      text: "",
    },
    xAxis: {
      title: {
        text: null,
      },
      labels: {
        style: {
          color: "#AFECFF",
          fontSize: 10 * scale,
        },
      },
      lineColor: "#85b4d0",
      type: "datetime",
      dateTimeLabelFormats: {
        millisecond: "%H:%M:%S.%L",
        second: "%H:%M:%S",
        minute: "%H:%M",
        hour: "%H:%M",
        day: "%m-%d",
        week: "%m-%d",
        month: "%Y-%m",
        year: "%Y",
      },
    },
    yAxis: {
      title: {
        text: null,
      },
      labels: {
        style: {
          color: "#AFECFF",
          fontSize: 12 * scale,
        },
        formatter: function() {
          return this.value + unit;
        },
      },
      minorGridLineWidth: 0,
      lineWidth: 0,
      tickWidth: 0,
      tickPosition: "inside",
      tickmarkPlacement: "between",
      tickColor: "#AFECFF",
      gridLineWidth: 1,
      gridLineColor: "#57789a",
      // tickInterval:10
    },
    legend: {
      enabled: true,
      align: "right",
      float: true,
      verticalAlign: "top",
      itemStyle: {
        color: "#AFECFF",
        fontSize: 12 * scale + "px",
      },
      itemHoverStyle: {
        color: "#ffffff",
      },
      // itemMarginBottom: 5*scale,
      // squareSymbol: false,
      symbolWidth: 24 * scale,
      // symbolHeight: 2*scale,
      // symbolPadding: 5*scale,
      symbolRadius: 2 * scale,
      // lineHeight: 0,
      // width: '60%'
    },
    tooltip: {
      shared: true,
      valueSuffix: unit || "",
      dateTimeLabelFormats: {
        millisecond: "%H:%M:%S.%L",
        second: "%H:%M:%S",
        minute: "%H:%M",
        hour: "%H:%M",
        day: "%Y-%m-%d",
        week: "%m-%d",
        month: "%Y-%m",
        year: "%Y",
      },
    },
    plotOptions: {
      spline: {
        dataLabels: {
          enabled: false,
        },
        marker: {
          enabled: true,
          radius: 1 * scale,
          lineWidth: 1,
        },
        pointInterval: 3600000, // one hour
      },
    },
    series: data.series,
  };
  HighCharts.chart(id, options);
}

function renderPie(opts) {
  let { id, chartData, scale, width, height } = opts;
  scale = scale || 1;
  if (!chartData) return;
  width = scale * width;
  height = scale * height;
  let data = chartData;
  let options = {
    credits: {
      enabled: false,
    },
    colors: ["#5B8FF9", "#5AD8A6", "#F6BD16", "#5D7092"],
    chart: {
      width: width,
      height: height,
      type: "pie",
      backgroundColor: "transparent",
      spacing: 0,
      margin: [5 * scale, 120 * scale, 5 * scale, 10 * scale],
    },
    title: {
      text: "",
    },
    plotOptions: {
      pie: {
        innerSize: "60%",
        dataLabels: {
          enabled: true,
          allowOverlap: true, // 允许数据标签重叠
          color: "#AFECFF",
          borderWidth: 0,
          style: {
            fontSize: 12 * scale + "px",
          },
          distance: 20 * scale,
          format: "{point.percentage:.1f} %",
        },
        borderWidth: 0,
        showInLegend: true,
      },
    },
    series: [
      {
        name: "数量",
        data: data,
      },
    ],
    legend: {
      enabled: true,
      align: "right",
      layout: "vertical",
      floating: true,
      verticalAlign: "middle",
      itemStyle: {
        color: "#AFECFF",
        fontSize: 12 * scale + "px",
      },
      itemMarginTop: 10 * scale,
      itemHoverStyle: {
        color: "#ffffff",
      },
    },
    // tooltip: {
    //  	formatter: function () {
    //  		return '<b>' + this.point.name + '</b>: ' + this.point.y + '%'
    //  	}
    // },
  };
  HighCharts.chart(id, options);
}
function renderGauge(opts) {
  let id = opts.id;
  let data = opts.data;
  let scale = opts.scale;
  let plotBands = opts.plotBands;

  let options = {
    credits: {
      enabled: false,
    },
    chart: {
      width: 220 * scale,
      height: 220 * scale,
      type: "gauge",
      backgroundColor: "transparent",
      spacing: 0,
      margin: [30 * scale, 0, 0, 0],
      plotBackgroundImage: null,
      plotBorderWidth: 0,
      plotShadow: false,
    },
    title: {
      text: "",
    },
    pane: {
      startAngle: -150,
      endAngle: 150,
      background: [
        {
          backgroundColor: "#01255e",
          borderWidth: 0,
          innerRadius: "60%",
          outerRadius: "100%",
          shape: "arc",
        },
      ],
    },
    // the value axis
    yAxis: {
      min: 0,
      max: opts.max || 0.6,
      minorTickInterval: "auto",
      minorTickWidth: 1,
      minorTickLength: 10,
      minorTickPosition: "inside",
      minorTickColor: "#cdd6e7",
      tickPixelInterval: 30,
      tickWidth: 2,
      tickPosition: "inside",
      tickLength: 10,
      tickColor: "#cdd6e7",
      labels: {
        step: 2,
        rotation: "auto",
        style: { color: "#cdd6e7", fontSize: 10 * scale + "px" },
      },
      title: {
        text: opts.title,
        style: { color: "#cdd6e7", fontSize: 12 * scale + "px" },
        y: 20 * scale,
      },
      plotBands: plotBands,
    },
    plotOptions: {
      gauge: {
        dial: {
          backgroundColor: "#fff",
        },
      },
    },
    series: [
      {
        name: opts.type,
        data: [
          {
            y: data,
            dial: {
              backgroundColor: "#fff",
            },
            dataLabels: {
              zIndex: 1000,
              y: 10 * scale,
              style: {
                fontSize: 8 * scale + "px",
                color: "#cdd6e7",
              },
              // useHTML: true,
              // formatter: function () {
              // 	var y = this.y;
              // 	return '<span style="color:#cdd6e7;font-size:8px;">' + y + ' MPa</span><br/>';
              // }
            },
          },
        ],
        tooltip: {
          valueSuffix: " MPa",
        },
      },
    ],
  };
  HighCharts.chart(id, options);
}

export default {
  name: "deviceDetailBasic",
  props: {
    scale: {
      type: Number,
      default: 1,
    },
    id: {
      // 设备ID
      type: String,
      default: "",
    },
    classify: {
      //物联网类型
      type: String,
      default: "1",
    },
    number: {
      //物联网设备编号
      type: String,
      default: "1",
    },
  },
  components: {
    deviceExport,
  },
  data() {
    var settingNumber = (rule, value, callback) => {
      const reg = /^\d+.?\d{0,2}$/;
      if (!value) {
        callback(new Error("请输入"));
      } else if (!Number(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("小数点后最多只能输入两位"));
        }
      }
    };
    return {
      recentWeek: [],
      activeDateIndex: 6,
      deviceDetail: {},
      alarmData: {},
      dataList: [],
      stateArr: [
        {
          class: "green",
          name: "正常",
        },
        {
          class: "red",
          name: "报警",
        },
        {
          class: "gray",
          name: "离线",
        },
        {
          class: "gray",
          name: "故障",
        },
      ],
      stateArr2: [
        {
          class: "org",
          name: "故障",
        },
        {
          class: "green",
          name: "正常",
        },
      ],
      pieChartData: [],
      isInit: true,
      poolShowType: "",
      switchList: [],
      switchLoading: false,
      tableData: [
        {
          id: "1001",
          variable: "上限报警",
          slaveName: "测控箱",
          time: "2023-06-28 11:07:51",
          current: "0.5",
        },
        {
          id: "1001",
          variable: "上限报警",
          slaveName: "测控箱",
          time: "2023-06-28 11:07:51",
          current: "0.5",
        },
        {
          id: "1001",
          variable: "上限报警",
          slaveName: "测控箱",
          time: "2023-06-28 11:07:51",
          current: "0.5",
        },
        {
          id: "1001",
          variable: "上限报警",
          slaveName: "测控箱",
          time: "2023-06-28 11:07:51",
          current: "0.5",
        },
      ],
      variableList: [
        {
          name: "设定上上限报警值",
          number: "",
          type: "upperLimitAlarmSettingValues",
          instructions: "02",
        },
        {
          name: "设定上限报警值",
          type: "upperLimitAlarmSettingValue",
          number: "",
          instructions: "03",
        },
        {
          name: "设定下限报警值",
          number: "",
          type: "lowerLimitAlarmSetPoint",
          instructions: "04",
        },
        {
          name: "设定下下限报警值",
          number: "",
          type: "lowerLimitAlarmSetPoints",
          instructions: "05",
        },
        {
          name: "设定启动值",
          number: "",
          type: "startValue",
          instructions: "06",
        },
        {
          name: "设定停止值",
          number: "",
          type: "stopValue",
          instructions: "07",
        },

        {
          name: "控制切换",
          number: "",
          type: "manualAutomaticState",
          instructions: "08",
        },
      ],
      exportVisible: false,
      setupModalVisible: false,
      rules: {
        settingNumber: [{ validator: settingNumber, trigger: "blur" }],
      },
      ruleForm: {
        settingNumber: "",
      },
      options: [
        {
          label: "自动",
          value: 1,
        },
        {
          label: "关闭",
          value: 2,
        },
        {
          label: "手动开",
          value: 3,
        },
      ],
      seriesData: "",
      deviceDetails: {},
      fireStatus: {},
    };
  },
  created() {
    this.openSocket();
    this.getRencentWeek();
    this.getData();
  },
  methods: {
    getGasFireExtinguishingData() {
      this.$get("/fireFightingIOT/device/getGasFireExtinguishingData", {
        number: this.number,
      })
        .then((res) => {
          this.fireStatus = res.data;
        })
        .catch((err) => {});
    },
    typeJudgment() {
      return (
        this.deviceDetail.deviceType == "30" ||
        (this.deviceDetail.deviceType == "34" &&
          this.deviceDetail.productId == "2010")
      );
    },
    isWireless() {
      return (
        this.deviceDetail.deviceType == "34" &&
        this.deviceDetail.productId == "2010"
      );
    },
    openSocket() {
      socket = io(this.config.socketUrl, { path: "/socket.io" });
      let uid = "1111";
      socket.on("connect", function() {
        console.log("connect");
      });
      socket.on("disconnect", function() {
        console.log("disconnect");
      });
      socket.on("new_msg", (msg) => {
        let dataArr = msg.split(",");
        let pointData = {};
        dataArr.forEach((item) => {
          let temp = item.split("=");
          pointData[temp[0]] = temp[1];
        });
        if (
          this.typeJudgment() &&
          pointData.dataType == "2" &&
          pointData.number == this.deviceDetail.number
        ) {
          this.getData("Refresh");
        }
      });
      socket.open();
    },
    getSwitch() {
      this.switchLoading = true;
      this.$get("/fireFightingIOT/switch/deviceSwitchList", {
        transDeviceCode: this.deviceDetail.transDeviceCode,
      })
        .then((res) => {
          this.switchLoading = false;
          this.switchList = res.data;
        })
        .catch((err) => {
          this.switchLoading = false;
        });
    },
    async getData(val) {
      let activeDate = this.recentWeek[this.activeDateIndex];
      this.openFullLoading();
      if (this.classify == 7) {
        this.getGasFireExtinguishingData();
      }
      await this.$post("/fireFightingIOT/device/normalDataLogList", {
        deviceClassify: this.classify,
        deviceId: this.id,
        time: `${activeDate.year}-${activeDate.month}-${activeDate.date}`,
        tabflag: 1,
      }).then(
        (res) => {
          this.closeFullLoading();
          this.deviceDetail = res.data.deviceDetail || {};
          this.alarmData = res.data.alarmData || {};
          this.dataList = res.data.oneList || [];
          if (this.typeJudgment()) {
            this.getEquipmentOverview(this.number);
          }
          if (this.classify != 19) {
            if (this.classify == 2) {
              this.poolShowType =
                waterGageTypes.indexOf(this.deviceDetail.deviceTypeName) >= 0
                  ? "水压"
                  : "水位";
            }

            this.$nextTick(() => {
              if (this.isInit) {
                // this.renderAlarm ()
                this.isInit = false;
              }

              this.renderCharts();
            });
          } else {
            this.getSwitch();
          }
        },
        (err) => {
          this.closeFullLoading();
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
      // this.getEquipmentOverview(this.deviceDetail.number)
    },
    renderAlarm() {
      if (!this.alarmData.todayCurrentCount) return;
      this.pieChartData = [
        ["电流报警", this.alarmData.todayCurrentCount],
        ["温度报警", this.alarmData.todayTemperatureCount],
        ["电压报警", this.alarmData.todayVoltageCount],
        ["漏电流报警", this.alarmData.todayLeakageCurrentCount],
      ];
      renderPie({
        id: "alarmChart",
        chartData: this.pieChartData,
        width: 440,
        height: 220,
        scale: this.scale,
      });
    },
    renderCharts() {
      for (let i = 0; i < this.dataList.length; i++) {
        if (this.poolShowType == "水压") {
          this.renderGaugeChart(i);
        } else {
          this.renderBarChart(i);
        }
        this.renderLineChart(i, this.classify == 2);
      }
    },
    renderBarChart(index) {
      let data = Object.assign({}, this.dataList[index]);
      let twoList = [...data.twoList];
      if (this.poolShowType == "水位") {
        twoList = twoList.filter((item) => {
          return item.displayName == this.poolShowType;
        });
      }
      let series = [
        {
          name: data.name,
          data: twoList.map((item) => {
            return +item.value;
          }),
        },
      ];

      let categories = twoList.map((item) => item.displayName);
      let chartData = {
        categories,
        series,
      };
      this.seriesData = series[0].data[0];
      if (!this.typeJudgment()) {
        this.utils.renderBar({
          id: "barChart" + index,
          chartData: chartData,
          width: 200,
          height: 220,
          scale: this.scale,
        });
      }
    },
    renderLineChart(index, isPool) {
      let data = [...this.dataList[index].twoList];
      let unit = "";
      if (isPool) {
        let showType =
          waterGageTypes.indexOf(this.deviceDetail.deviceTypeName) >= 0
            ? "水压"
            : "水位";
        if (showType == "水压") {
          unit = "MPa";
        } else if (this.typeJudgment()) {
          unit = this.deviceDetail.unit;
        } else {
          unit = "米";
        }
        data = data.filter((item) => {
          return item.displayName == showType;
        });
      }
      let series = [];
      let categories = data[0].valueList.map((item) => item.sendtime);
      data.forEach((item) => {
        let valueList = item.valueList;
        series.push({
          name: this.typeJudgment() ? "当前数据" : item.name,
          data: valueList.map((item) => {
            let activeDate = this.recentWeek[this.activeDateIndex];
            // console.log(activeDate,4444);
            let time = item.sendtime.split(":");
            // time = [time[0],time[1]]
            let date = Date.UTC(
              activeDate.year,
              activeDate.month - 1,
              activeDate.date,
              +time[0],
              +time[1],
              0
            );
            return [date, +item.value];
          }),
        });
      });
      let chartData = {
        categories: categories,
        series: series,
      };
      renderSpline({
        id: "lineChart" + index,
        chartData: chartData,
        width: this.isWireless() ? 890 : 690,
        height: 220,
        scale: this.scale,
        unit: unit,
        // unit:this.deviceDetail.deviceType == '30'?this.deviceDetail.unit:unit,
      });
    },

    renderGaugeChart(index) {
      let data = Object.assign({}, this.dataList[index]);
      let datas = data.twoList || [];
      let showType =
        waterGageTypes.indexOf(this.deviceDetail.deviceTypeName) >= 0
          ? "水压"
          : "水位";
      let plotBands = {};
      let chartTitle = "";
      let chartMax = 0.6;
      if (showType == "水压") {
        plotBands = [
          {
            from: 0,
            to: 0.1,
            color: "#ff0400", // red
          },
          {
            from: 0.1,
            to: 0.5,
            color: "#11e366", // green
          },
          {
            from: 0.5,
            to: 0.6,
            color: "#ff0400", // red
          },
        ];
        chartTitle = "水压MPa";
        chartMax = 0.6;
      } else {
        plotBands = [
          {
            from: 0,
            to: 1,
            color: "#ff0400", // red
          },
          {
            from: 1,
            to: 5,
            color: "#11e366", // green
          },
          {
            from: 5,
            to: 10,
            color: "#ff0400", // red
          },
        ];
        chartTitle = "水位(米)";
        chartMax = 10;
      }
      let dataObj = datas.filter((item) => {
        return item.displayName == showType;
      });
      if (dataObj.length == 0) return;
      dataObj = dataObj[0];
      renderGauge({
        id: "gaugeChart" + index,
        data: +dataObj.value,
        scale: this.scale,
        plotBands: plotBands,
        title: chartTitle,
        type: showType,
        max: chartMax,
      });
    },

    formatDate(d) {
      let year = d.getFullYear();
      let month = d.getMonth() + 1;
      let date = d.getDate();
      return { year, month, date };
    },
    getRencentWeek() {
      const today = new Date();
      let dates = [];
      for (let i = 6; i >= 0; i--) {
        let thisDate = new Date();
        thisDate.setTime(thisDate.getTime() - 3600 * 1000 * 24 * i);
        dates.push(this.formatDate(thisDate));
      }
      this.recentWeek = dates;
    },
    changeDate(item, index) {
      this.activeDateIndex = index;
      this.getData();
    },
    exportAction() {
      this.exportVisible = true;
    },
    setupNumber(item) {
      if (this.deviceDetail.currentstate == 3) {
        return;
      }
      if (item == "01") {
        this.reset();
        return;
      }
      this.setupModalVisible = true;
      this.ruleForm.settingNumber = item.number;
      this.ruleForm.instructions = item.instructions;
    },
    getEquipmentOverview(number) {
      this.$get("/fireFightingIOT/device/getWaterColumnBoxData", {
        number,
      }).then((res) => {
        this.variableList.forEach((item) => {
          if (res.data.hasOwnProperty(item.type)) {
            this.$set(item, "number", res.data[item.type]);
          }
        });
        this.deviceDetails = res.data;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid || this.ruleForm.instructions == "08") {
          this.$post("/fireFightingIOT/device/setWaterColumnBoxData", {
            instructions: this.ruleForm.instructions,
            data: this.ruleForm.settingNumber,
            number: this.number,
          })
            .then((res) => {
              if (res.code == 0) {
                this.setupModalVisible = false;
                this.getEquipmentOverview(this.number);
                this.$message.success("设置成功");
              } else {
                this.$message.error("设置失败");
              }
            })
            .catch((err) => {
              this.$message.error("设置失败");
            });
        } else {
          return false;
        }
      });
    },
    reset() {
      this.$post("/fireFightingIOT/device/setWaterColumnBoxData", {
        instructions: "01",
        number: this.number,
      })
        .then((res) => {
          if (res.code == 0) {
            this.setupModalVisible = false;
            this.getEquipmentOverview(this.number);
            this.$message.success("采集成功");
          } else {
            this.$message.error("采集失败");
          }
        })
        .catch((err) => {
          this.$message.error("采集失败");
        });
    },
  },
  destroyed() {
    socket.close();
  },
};
</script>
